/*
 * COPYRIGHT:	2010 Christopher Smith, licenced under the GNU GPL v2; see COPYING in the top level directory
 * PROJECT:		sdedit
 * FILE:		dialogbase.cpp
 * PURPOSE:		base class for dialog windows (as opposed to classed windows)
 *				
 */

class DialogWindowBase : public WindowBase
{
	BOOLEAN LastMessageHandled;

	static INT_PTR DialogWndProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam)
	{
		WindowBase *wob;

		if(WindowBase::GetWindowObject(wob, wnd, msg, wparam, lparam))
		{
			wob->inc_ref();

			DialogWindowBase *wo = static_cast<DialogWindowBase *>(wob);

			wo->LastMessageHandled = TRUE;

			LRESULT result = 0;

			__try
			{
				if(msg == WM_PRE_PROCESS)
					result = wo->QueryPreProcess(wparam, lparam);
				else
					result = wo->RecieveMessage(wnd, msg, wparam, lparam);
			}
			__except(ShowErrorMessageBox(exception_info(), wnd))
			{}

			if(wo->LastMessageHandled)
			{
				SetWindowLongPtr(wnd, DWLP_MSGRESULT, result);
				wob->dec_ref();
				return TRUE;
			}

			wob->dec_ref();
			return FALSE;
		}
		else
			return FALSE;
	}

protected:
	void Create(HINSTANCE Instance, LPCWSTR Template, HWND Parent)
	{
		Wnd = NULL;
		HWND LateWnd = NULL;

		inc_ref(); //the reference from the underlying window

		PrepareForCreate();

		LateWnd = CreateDialog(Instance, Template, Parent, &DialogWndProc); 

		if(!Wnd)
		{
			Wnd = LateWnd;
			SetWindowLongPtr(Wnd, GWLP_USERDATA, (ULONG_PTR)this);
			Init();
		}
	}

	INT_PTR CreateModal(HINSTANCE Instance, LPCWSTR Template, HWND Parent)
	{
		inc_ref(); //the reference from the underlying window

		PrepareForCreate();

		return DialogBox(Instance, Template, Parent, &DialogWndProc);

		return -1;
	}
	
	virtual LRESULT RecieveMessage(HWND wnd, UINT message, WPARAM wparam, LPARAM lparam) override
	{
		LastMessageHandled = FALSE;
		
		return 0;
	}
};